<template>
  <div class="login-container">
    <el-form
      :model="user"
      ref="refForm"
      :rules="loginFormRules"
      class="login-form"
    >
      <h2 class="login-title">扶贫助农平台</h2>
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="user.username"
          placeholder="长度5-10"
          class="login-input"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="user.password" class="login-input"></el-input>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button type="primary" @click="submitForm('refForm')"
          >登录</el-button
        >
        <el-button type="warning">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
    data () {
        return {
            user:{
                username:'',
                password:''
            },
            loginFormRules:{
                username:[
                    // 表示当鼠标失去焦点的时候，验证，必填项，如果为空，则显示message中的内容
                    {required:true,message:'用户名不能为空',trigger:'blur'},
                    {min:1,max:10,message:'用户名1-10位',trigger:'blur'}
                ],
                password:[
                    {required:true,message:'密码不能为空',trigger:'blur'},
                    {min:1,max:10,message:'密码1-10位',trigger:'blur'}
                ]
            }
        }
    },
    methods: {
        submitForm(refForm){
            this.$refs[refForm].validate(async(ispass)=>{
                if(ispass){
                    let params = new URLSearchParams()
                    params.append('username',this.user.username)
                    params.append('password',this.user.password)
                    let { data : res} = await this.$axios.post('/user/login',params)      
                    console.log(res);
                    if(res.code == 200){
                        this.$message.success('登录成功')
                        //跳转主页,保存token
                        window.sessionStorage.setItem('token',res.data.token)
                        // 保存id
                        window.sessionStorage.setItem("id", res.data.id);
                        this.$router.push('/index')
                    }else{
                        this.$message.error('用户名或者密码错误');
                        return
                    }  
                }else{
                    return
                }
            })
        }
    }
}
</script>

<style scoped>
/* scoped:当前样式，不继承 */
.login-container {
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgb(132, 191, 197);
}
.login-form {
  width: 30%;
  margin: 100px auto;
  background-color: rgb(255, 255, 255, 0.6); /*透明背景色 */
  border-radius: 20px;
  padding: 20px;
}
.login-title {
  color: #333;
  text-align: center;
}
.login-input {
  width: 85%;
}
</style>